<?php

namespace Addons\Slog\Controller;
use Home\Controller\AddonsController;

class SlogController extends AddonsController{

	public function index(){
		$this->assign('slog_count', M('Slog')->count());
		$this->display(ONETHINK_ADDON_PATH.'Slog/index.html');
	}

	public function debug(){
		C('SHOW_PAGE_TRACE', false);
		$config = get_addon_config('Slog');
		$retry = ($config['timeout'] -1)* 1000;
		$sep_time = $config['timeout'];
		header("Content-Type: text/event-stream");
		header("Cache-Control: no-cache");
		header("Access-Control-Allow-Origin: *");

		$lastEventId = floatval(isset($_SERVER["HTTP_LAST_EVENT_ID"]) ? $_SERVER["HTTP_LAST_EVENT_ID"] : 0);
		if ($lastEventId == 0) {
			$lastEventId = floatval(isset($_GET["lastEventId"]) ? $_GET["lastEventId"] : 0);
		}

		echo ":" . str_repeat(" ", 2048) . "\n"; // 2 kB padding for IE
		echo "retry: {$retry}\n";

		// event-stream
		$i = $lastEventId;
		$map  = 'datetime > '.strtotime("-{$config['timeout']} seconds");
		$logs = M('Slog')->where($map)->select();
		echo "id: " . $i . "\n";
		if(!empty($logs))
			foreach ($logs as $key => $value) {
				$data = nl2br($value['message']);
				$data = str_replace("\r", '', $data);
				$data = str_replace("\n", '', $data);
				echo ('data:'.json_encode($data)."\n\n");
			}
		ob_flush();
		flush();
	}

	public function clear(){
		M('')->execute('TRUNCATE TABLE '.C('DB_PREFIX').'slog');
		$this->success();
	}
}
